import {Component, OnInit} from '@angular/core';
import {AliyunOssOutputUrl, appletApiUrl} from '../../../../config/api';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {isInteger} from '@ng-bootstrap/ng-bootstrap/util/util';
import {ActivatedRoute, Router} from '@angular/router';
import {DisplayService} from '../display.service';
import {GroupService} from '../../group/group.service';
import {NzMessageService} from 'ng-zorro-antd';
import {AdOssUploadService} from '../../../lib/service/ad-oss-upload.service';
import {LocalStorageService} from '../../../lib/service/local-storage.service';


@Component({
  selector: 'app-edit1',
  templateUrl: './edit1.component.html',
  styleUrls: ['./edit1.component.scss'],
  providers: [NzMessageService, GroupService]
})
export class Edit1Component implements OnInit {


  validateForm: FormGroup;
  fileList = [];
  picList = [];
  showCaseId;
  id;
  boothNumber;
  loadingInfo: boolean;
  name: string;
  types = 0;
  stage = 2;
  status1 = 1;

  aliyunOssOutputUrl = AliyunOssOutputUrl;

  picSizeInfo;

  submitStatus = false;

  //右侧预览区块
  previewTitle;
  previewsubTitle;
  previewSrc;
  page = 1;
  pageSize = 5;


  /* 商品弹窗 */
  goodsModalVisible = false;
  goodsList = [];
  groupList = [];
  selectedGroup;
  keyword;
  currentClickGoods = {};
  checkedGoodsInfo = {};
  total;
  status = '上架';
  loading = false;
  currentGoodsPrice = 0;
  comparePriceStatus = false;
  skuStatus = false;
  highPriceSkuId = null;
  ghostData = null;
  randomStatus = false;
  activity_goods_prize;


  //活动弹窗
  activityModalVisible = false;
  activityList = [];
  activityLoading = false;
  activitiesTotal;
  currentClickActivity = {};
  checkedActivityInfo = {};
  activityClickIndex;
  self = this;


  //卡券弹窗
  couponModalVisible = false;
  couponList = [];
  couponLoading = false;
  couponsTotal;
  currentClickCoupon = {};
  checkedCouponInfo = {};
  couponKeyWord = '';
  couponClickIndex;
  showcase_id;
  selectedOption;


  urlReg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;

  type = '';

  f1 = ['showcaseDetail'];

  template_id;

  appOptions = ['page', 'activity', 'coupons', 'product', 'picture'];
  options = [
    {'label': '商品', value: 1}
  ];
  shopid: any;
  banner_detail: string;
  pic_url: any;
  banner_id: any;

  getFormControl(name) {
    return this.validateForm.controls[name];
  }


  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (!isInteger(control.value)) {
        observer.next({error: true, notInteger: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }
  //价格验证
  priceValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value > this.currentGoodsPrice) {
        observer.next({error: true, priceToHigh: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  };
  // url验证
  urlValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value == '' || control.value == null) {
        observer.next(null);
      } else if (!this.urlReg.test(control.value)) {
        observer.next({error: true, urlError: true});
      } else {
        observer.next(null);
      }
      observer.complete();

    })
  };


  constructor(private routeInfo: ActivatedRoute,
              public displayService: DisplayService,
              private fb: FormBuilder,
              private groupService: GroupService,
              private _message: NzMessageService,
              private router: Router,
              private adOssUploadService: AdOssUploadService,
              private localStorageService: LocalStorageService,
              private activatedRoute: ActivatedRoute
  ) {
    this.validateForm = this.fb.group({
      'name': ['', [Validators.required]],
      // 'showcase_id': ['', [Validators.required]],
      'goto_type': [1, Validators.required],
      'sort': ['', [Validators.required, Validators.min(0), Validators.max(99)], this.integerValidators],
      'goto': [''],
      // 'relationID': ['']
    });

  }

  ngOnInit() {
    this.shopid = this.localStorageService.getShop()['id'];
    const data = JSON.parse(localStorage.getItem('banner_item'));
    console.log('b-de', data);
    this.validateForm.controls['name'].setValue(data.name);
    this.validateForm.controls['sort'].setValue(data.sort);
    this.validateForm.controls['goto'].setValue(data.goto);
    this.validateForm.controls['goto_type'].setValue(data.goto_type);
    this.selectedOption = this.options.filter(val => val.value === data.goto_type)[0];
    // this.selectedOption = {'label':,'value':data.goto_type};
    this.banner_id = data.id;
    console.log('this.selectedOption', this.selectedOption);
    if (data.pic_url_s) {
      this.picList.push({src: data.pic_url_s});
      this.pic_url = data.pic_url;
    }

  }

  //根据type去获取请求对应的列表
  // switchTypeList(type) {
  //   return this.typesArr[type];
  // }

  //loadingSwitch
  // loadingSwitchData(data) {
  //   this.pageSize = 100;
  //   this.options.map((e) => {
  //     if (e.value === data.type) {
  //       this.selectedOption = e;
  //       switch (data.type) {
  //         case 'product':
  //           if(data.relationID) {
  //             this.getGoodsList().then(() => {
  //               this.goodsList.map((e, i) => {
  //                 if (e.id == data.relationID) {
  //                   this.checkedGoodsInfo = this.currentClickGoods = e;
  //                   this.loadingInfo = false;
  //                   this.pageSize = 5;
  //                 } else {
  //                   this.loadingInfo = false;
  //                 }
  //               })
  //             }).catch((res) => {
  //               this.loadingInfo = false;
  //             });
  //           } else {
  //             this.loadingInfo = false;
  //           }
  //           break;
  //         case 'picture':
  //           this.getActivityList().then(() => {
  //             this.getActivityInfo(data);
  //           }).catch((res) => {
  //             this.loadingInfo = false;
  //           });
  //           break;
  //         case 'activity':
  //           this.getActivityList().then(() => {
  //             this.getActivityInfo(data);
  //           }).catch((res) => {
  //             this.loadingInfo = false;
  //           });
  //           break;
  //         case 'coupons':
  //           if(data.relationID) {
  //             this.getCouponList().then(() => {
  //               this.couponList.map((e, i) => {
  //                 if (e.card_coupons_uuid == data.relationID) {
  //                   this.checkedCouponInfo = this.currentClickCoupon = e;
  //                   this.loadingInfo = false;
  //                   this.pageSize = 5;
  //                 } else {
  //                   this.loadingInfo = false;
  //                 }
  //               })
  //             }).catch((res) => {
  //               this.loadingInfo = false;
  //             });
  //           } else {
  //             this.loadingInfo = false;
  //           }
  //           break;
  //         default:
  //           this.loadingInfo = false;
  //       }
  //     }
  //   });
  // }


  // getActivityInfo(data) {
  //   let activity = data['activity'];
  //   let goods = activity['activity_goods'][0];
  //   this.checkedActivityInfo = activity;
  //   this.checkedActivityInfo['type'] = this.typeText[goods['type']];
  //   this.checkedActivityInfo['goodsDetail'] = goods['goods'];
  //   this.loadingInfo = false;
  //   this.pageSize = 5;
  // }

  //切换选择类型
  checkType(e) {
    if (!e) {
      let controlValue = this.validateForm.controls['goto_type'].value;
      let selectedValue = this.selectedOption.value;
      if (controlValue !== selectedValue) {
        this.validateForm.controls['goto_type'].setValue(selectedValue);
      }
    }
  };


  /* 商品弹窗逻辑 */

  // 获取商品列表
  // getGoodsList() {
  //   this.loading = true;
  //   this.getGroupList();
  //   return new Promise((resolve, reject) => {
  //     this.groupService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.keyword, this.status).subscribe(res => {
  //       if (res.code === 2000) {
  //         this.total = res.data.total;
  //         const goodsList = res.data.data;
  //         const goodsId = [];
  //         goodsList.forEach(item => {
  //           goodsId.push(item.id);
  //         });
  //         this.groupService.getbindListAll('[' + goodsId.join(',') + ']').subscribe(rs => {
  //           if (rs.code === 2000) {
  //             const goodsjson = {};
  //             rs.data.forEach(item => {
  //               if (!goodsjson[item.goods_id]) {
  //                 goodsjson[item.goods_id] = [item.name];
  //               } else {
  //                 goodsjson[item.goods_id].push(item.name);
  //               }
  //             });
  //             goodsList.forEach(item => {
  //               if (item.goods_number) {
  //                 item.goods_number = item.goods_number.split('|');
  //               }
  //               item.goods_category = goodsjson[item.id];
  //             });
  //           }
  //           this.goodsList = goodsList;
  //           resolve(this.goodsList);
  //           this.loading = false;
  //         });
  //       } else {
  //         this._message.create('error', res.message);
  //       }
  //       this.loading = false;
  //     });
  //   })
  // }

  // 获取店铺商品类型列表
  // getGroupList() {
  //   this.groupService.getGroupList().subscribe(res => {
  //     this.groupList = res.data.data;
  //   });
  // }

  // 搜索商品
  // searchGoods() {
  //   this.page = 1;
  //   this.getGoodsList();
  // }

  // 添加商品
  // addGoods() {
  //   this.currentClickGoods = JSON.parse(JSON.stringify(this.currentClickGoods));
  //   this.goodsModalVisible = true;
  //   this.page = 1;
  //   this.pageSize = 5;
  //   this.keyword = '';
  //   this.switchTypeList(this.selectedOption.value)();
  // }

  // 关闭添加商品弹窗
  // closeModal() {
  //   this.currentClickGoods = JSON.parse(JSON.stringify(this.checkedGoodsInfo));
  //   this.goodsModalVisible = false;
  // }

  // 确认选择商品
  // confirmCheckedGoods() {
  //   if (!Object.keys(this.currentClickGoods).length) {
  //     this._message.create('error', '请选择商品');
  //     return;
  //   }
  //   this.checkedGoodsInfo = JSON.parse(JSON.stringify(this.currentClickGoods));
  //   this.validateForm.controls['relationID'].setValue(this.checkedGoodsInfo['id'] + '');
  //   this.groupService.getGoodsSkuList(this.currentClickGoods['id'], 100).subscribe(res => {
  //     if (res.code === 2000) {
  //       const sku = res.data.data;
  //       const activity_goods_prize = [];
  //       sku.map((val, idx) => {
  //         val.checked = true;
  //         const sku_item = {'sku_id': val.id, 'number': val.in_stock};
  //         activity_goods_prize.push(sku_item);
  //       });
  //       this.activity_goods_prize = activity_goods_prize;
  //       this.checkedGoodsInfo['sku'] = sku;
  //       this.goodsModalVisible = false;
  //     } else {
  //       this._message.create('error', res.message);
  //     }
  //   });
  // }


  /*活动弹窗逻辑*/

  // 获取活动列表
  // getActivityList() {
  //   this.activityLoading = true;
  //   return new Promise((resolve, reject) => {
  //     this.displayService.getActivityList(this.page, this.pageSize, this.keyword, this.types, this.stage, this.status1).subscribe(res => {
  //       if (res.code === 2000) {
  //         this.activityList = res.data.data;
  //         this.activityList.map((e, i) => {
  //           e['flexable'] = false;
  //         });
  //         this.activitiesTotal = res.data.total;
  //         this.activityLoading = false;
  //         resolve();
  //       }
  //     })
  //
  //   })
  // }

  //搜索活动
  // searchActivity() {
  //   this.page = 1;
  //   this.getActivityList();
  // }

  //打开活动模态框
  // addActivity() {
  //   this.currentClickActivity = this.checkedActivityInfo;
  //   this.activityModalVisible = true;
  //   this.page = 1;
  //   this.pageSize = 5;
  //   this.keyword = '';
  //   this.switchTypeList(this.selectedOption.value)();
  // }

  //关闭活动模态框
  // closeActivityModal() {
  //   this.activityModalVisible = false;
  //   this.activityList.map((e, i) => {
  //     e['flexable'] = false;
  //   });
  // }

  //确认活动模态框
  // confirmCheckedActivity() {
  //   this.checkedActivityInfo = this.currentClickActivity;
  //   this.checkedActivityInfo['flexable'] = false;
  //   this.checkedActivityInfo['type'] = this.typeText[this.currentClickActivity['activity_goods'][0]['type']];
  //   this.validateForm.controls['relationID'].setValue(this.checkedActivityInfo['id'] + '');
  //   this.activityList.map((e, i) => {
  //     e['flexable'] = false;
  //   });
  //   this.activityModalVisible = false;
  // }

  //获取活动商品列表
  // getActivityGoodsList(activityId, activityGoodsId) {
  //   this.displayService.getActivityGoodsList(activityId, activityGoodsId).subscribe(res => {
  //     if (res.code === 2000) {
  //       this.activityList[this.activityClickIndex]['goodsDetail'] = res.data;
  //     }
  //   })
  // }

  //查看活动商品
  // toggleFlexable(i) {
  //   this.activityClickIndex = i;
  //   let target = this.activityList[i];
  //   target['flexable'] = !target['flexable'];
  //   if (target['flexable']) {
  //     let activityId = target['id'], activity_goods_id = target['activity_goods'][0]['id'];
  //     this.getActivityGoodsList(activityId, activity_goods_id);
  //   }
  // }

  //切换checked查看商品
  // toggleViewActivityGoods() {
  //   this.checkedActivityInfo['flexable'] = !this.checkedActivityInfo['flexable'];
  // }


  /*卡券弹窗逻辑*/
  // addCoupon() {
  //   this.couponModalVisible = true;
  //   this.page = 1;
  //   this.pageSize = 5;
  //   this.keyword = '';
  //   this.switchTypeList(this.selectedOption.value)();
  // }

  //获取卡券列表
  // getCouponList() {
  //   return new Promise((resolve, reject) => {
  //     this.displayService.getCouponList(this.page, this.pageSize, this.keyword).subscribe(res => {
  //       if (res.code === 2000) {
  //         this.couponList = res.data.data;
  //         this.couponsTotal = res.data.total;
  //         resolve();
  //       }
  //     });
  //   });
  // }

  //搜索卡券
  // searchCoupon() {
  //   this.page = 1;
  //   this.switchTypeList(this.selectedOption.value)();
  //   // this.getCouponList();
  // }

  //关闭卡券模态框
  // closeCouponModal() {
  //   this.couponModalVisible = false;
  //   this.currentClickCoupon = this.checkedCouponInfo;
  // }

  //确认卡券模态框信息
  // confirmCheckedCoupon() {
  //   this.checkedCouponInfo = this.currentClickCoupon;
  //   this.validateForm.controls['relationID'].setValue(this.checkedCouponInfo['card_coupons_uuid'] + '');
  //   this.couponModalVisible = false;
  // }


  //重置
  // reset() {
  //   this.keyword = '';
  //   this.page = 1;
  //   this.pageSize = 5;
  //   this.selectedGroup = null;
  //   this.switchTypeList(this.selectedOption.value)();
  // }

  // uploadImg(showcase_detail_id) {
  //   this.adOssUploadService
  //     .getSignature(`/v1/common/showcase_detail/${showcase_detail_id}?callback=true`)
  //     .subscribe(
  //       res1 => {
  //         let length = this.fileList.filter(item => {
  //           return item && item != 'pic';
  //         }).length;
  //         let successLen = 0;
  //         if (length == 0) {
  //           this.submitStatus = false;
  //           this._message.create('success', '修改成功');
  //           this.router.navigate(['member/display/list'],{
  //             queryParams: {
  //               showcaseId: this.showcase_id
  //             }
  //           });
  //           return false;
  //         }
  //         this.fileList.every((val, idx, array) => {
  //           if (val && val != 'pic') {
  //             this.adOssUploadService.fileUpload(val, res1.data, this.f1[idx] + '.' + val.name.replace(/.+\./, '').toLowerCase(), 'image')
  //               .subscribe(res2 => {
  //                   successLen++;
  //                   if (successLen == length) {
  //                     this.submitStatus = false;
  //                     this._message.create('success', '修改成功');
  //                     this.router.navigate(['member/display/list'],{
  //                       queryParams: {
  //                         showcaseId: this.showcase_id
  //                       }
  //                     });
  //                   }
  //                 }
  //               );
  //           }
  //           return true;
  //         });
  //
  //       }
  //     );
  // }

  picError = false; // 图片是否错误
  fileChange() {
    console.log('file-', this.fileList);
    if (this.fileList.length === 0 && this.picList.length === 0) {
      this.picError = true;
    } else {
      const length = this.fileList.filter(item => {
        return item && item !== 'pic';
      }).length;
      if (length === 0) {
        this.submitStatus = false;
        this._message.create('success', '添加成功');
        return false;
      }
      // @ts-ignore
      this.fileList.every(val => {
        this.adOssUploadService.fileUpload_(val, '1').subscribe(res => {
            this.picError = false;
            this.pic_url = res.data.filename_save;
            console.log('pic', this.pic_url);
          }
        );
      });

    }
  }


  // currentClick(data) {
  //   this.currentClickActivity = data;
  // }

  goBack() {
    this.router.navigate([`member/display/list`], {
      // queryParams: {
      //   showcaseId: this.showcase_id
      // }
    });
  }

  _submitForm() {
    console.log(this.validateForm.value);
    if (this.submitStatus) {
      return;
    }
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    this.fileChange();

    if (this.validateForm.valid && !this.picError) {
      this.submitStatus = true;
      this.validateForm.value.shop_id = this.shopid;
      this.validateForm.value.pic_url = this.pic_url;
      let data = this.validateForm.value;
      data.id = this.banner_id;
      this.displayService.editShowCaseDetail(data).subscribe(res => {
        if (res.code === 200) {
          this.submitStatus = false;
          // this.uploadImg(this.id);
          this.router.navigate(['member/display/list'], {
            queryParams: {
              id: this.shopid
            }
          });
        } else {
          this.submitStatus = false;
          this._message.create('error', res.message);
        }
      });
    }
  }
}
